package bjut.core.serializal;

import bjut.core.interfaces.Serializer;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/26 0:16
 */
public class ProtostuffSerializer implements Serializer {

    //避免每次序列化都重新申请Buffer空间
    private static final LinkedBuffer BUFFER = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);

    @Override
    public byte[] serialize(Object obj) {

        Class<?> aClass = obj.getClass();
        //schema就是一个组织结构，就好比是数据库中的表、视图等等这样的组织机构，在这里表示的就是序列化对象的结构。
        //获得这个类的Schema
        Schema schema = RuntimeSchema.getSchema(aClass);
        byte[] bytes;
        try {
            bytes = ProtostuffIOUtil.toByteArray(obj, schema, BUFFER);
        } finally {
            BUFFER.clear();
        }
        return bytes;
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> cls) {
        //据序列化对象获取其组织结构Schema。然后根据byte直接mergeFrom成一个对象。
        Schema<T> schema = RuntimeSchema.getSchema(cls);
        T t = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(bytes, t, schema);
        return t;
    }
}
